<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/8/15
 * Time: 12:43
 */

namespace backend\modules\manager\controllers;
use backend\controllers\BaseController;
use common\models\Business;
use Yii;
use yii\data\ArrayDataProvider;
use yii\db\Query;
use backend\modules\manager\models\BusinessForm;
use yii\filters\auth\CompositeAuth;
use yii\filters\ContentNegotiator;
use yii\filters\RateLimiter;
use yii\filters\VerbFilter;
use yii\web\Response;


/**
 * Class BusinessController
 * @package backend\modules\manager\controllers
 */
class BusinessController extends BaseController {

//    public $serializer = 'yii\rest\Serializer';
//
//    public function behaviors()
//    {
//        return [
//            /** 解析响应的内容格式 */
//            'contentNegotiator' => [
//                'class' => ContentNegotiator::className(),
//                'formats' => [
//                    'application/json' => Response::FORMAT_JSON,
//                    'application/xml' => Response::FORMAT_XML,
//                ],
//            ],
//            /** 校验请求方法 */
//            'verbFilter' => [
//                'class' => VerbFilter::className(),
//                'actions' => $this->verbs(),
//            ],
//            /** 检验用户权限 */
//            'authenticator' => [
//                'class' => CompositeAuth::className(),
//            ],
//            /** 限制速度 */
//            'rateLimiter' => [
//                'class' => RateLimiter::className(),
//            ],
//        ];
//    }
//
//    public function verbs()
//    {
//        return [];
//    }
//
//    public function serializeData($data)
//    {
//        return Yii::createObject($this->serializer)->serialize($data);
//    }
//    public function afterAction($action, $result)
//    {
//        $result = parent::afterAction($action, $result);
//        return $this->serializeData($result);
//    }

    /** 查询显示列 */
    public $selectParam = array(
        'id',
        'logo',
        'name',
        'licence',
        'read_num',
        'share_num',
        'phone',
        'created_at',
        'status'
    );

    /**
     * 后台获取商家列表接口
     * @param page 页数(从0开始)
     * @param pageSize 每页显示条数
     * @param name 商家名称
     * @param status 商家状态 -1已删除 0未审批 1已通过'
     * @return array
     */
    public function actionList()
    {
        /** 当前页数 从0开始 */
        $page = isset($this->postData['page']) ? intval($this->postData['page']) : 0;
        /** 每页显示条数 */
        $pageSize = isset($this->postData['pageSize']) ? intval($this->postData['pageSize']) : 10;

        /** 组装where查询条件 */
        $where = array();
        /** 商家名称 */
        if(isset($this->postData['name'])){
            $where['name'] = trim($this->postData['name']);
        }
        /** 商家状态 */
        if(isset($this->postData['status'])){
            $where['status'] = intval($this->postData['status']);
        }
        /** 定义查询对象 */
        $query = new Query();
        $provider = new ArrayDataProvider([
            'allModels' => $query->select($this->selectParam)
                ->from('business')
                ->where($where)->all(),
            'sort' => [
                'attributes' => ['id'],
            ],
            'pagination' => [
                'page' => $page,
                'pageSize' => $pageSize,
            ],
        ]);
        $datas = array();
        /** 获取数据 */
        $models = $provider->getModels();
        if($models){
            foreach($models as $key => $value){
                $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
                $datas[] = $value;
            }
        }
        /** 数据总条数 */
        $totalCount = $provider->getTotalCount();
        /** 返回数据 */
        $returnData = array();
        $returnData['list'] = $datas;
        $returnData['totalCount'] = $totalCount;
        return $this->responseFormat($returnData);
    }

    /**
     * 查询商家详情
     * @param id 商家Id
     * @return array
     */
    public function actionView()
    {
        /** 获取商家ID */
        $id = $this->postData['id'] == null ? 0 : intval($this->postData['id']);
        if(!$id){
            return $this->responseError('商家Id不能为空.');
        }

        /** 获取商家信息 */
        $business = Business::findIdentity(array('id' => $id));
        if(!$business){
            return $this->responseError('没有匹配到对应商家.');
        }
        /** 返回数据 */
        $returnData = array();
        $returnData['detail'] = $business;
        return $this->responseFormat($returnData);
    }

    /**
     * 添加商家其他信息接口
     * @param name 商家名称
     * @param phone 联系方式
     * @param logo logo图标路径
     * @param type 商家类型 1影楼 2工作室
     * @param province 省份
     * @param city 市
     * @param area 区
     * @param address 详细地址
     * @param location 地图坐标
     * @param licence 营业执照
     * @param id 商家Id
     */
    public function actionEdit()
    {
        /** 校验表单是否为空 */
        if(!$this->postData){
            return $this->responseError("参数信息为空.");
        }
        /** 校验id */
        if(empty($this->postData['id'])){
            return $this->responseError('Id is null');
        }
        /** 定义返回数据 */
        $resultData = array();
        /** 接收数据 */
        $businessForm = new BusinessForm();
        $businessForm->phone = $this->postData['phone'];
        $businessForm->logo = $this->postData['logo'];
        $businessForm->type = $this->postData['type'];
        $businessForm->province = $this->postData['province'];
        $businessForm->city = $this->postData['city'];
        $businessForm->area = $this->postData['area'];
        $businessForm->address = $this->postData['address'];
        $businessForm->location = $this->postData['location'];
        $businessForm->licence = $this->postData['licence'];

        /** 添加 */
        $bool = $businessForm->add();
        if($bool){
            /** 成功返回 */
            $resultData['id'] = $businessForm->getBusiness()->getId();
            $resultData['auth_key'] = $businessForm->getBusiness()->getAuthKey();
            return $this->responseFormat($resultData);
        }

        /** 失败返回 */
        if ($businessForm->errors) {
            foreach ($businessForm->errors as $key => $info) {
                $resultData[$key] = $info;
            }
        }
        return $this->responseError($resultData);
    }

    /**
     * 商家审批接口
     * @param id 商家Id
     * @param status 商家状态
     */
    public function actionAudit()
    {
        /** 校验表单是否为空 */
        if(!$this->postData){
            return $this->responseError("参数信息为空.");
        }
        /** 校验id */
        if(empty($this->postData['id']) || empty($this->postData['status'])){
            return $this->responseError('Id is null');
        }

        /** 获取商家信息 */
        $business = Business::findIdentity($this->postData['id']);
        if($business){
            $business['status'] = intval($this->postData['status']);
            /** 更新状态 */
            $bool = $business->save(false);
            if($bool){
                /** 成功返回 */
                $resultData = array(
                    'id' => $business->getId(),
                );
                return $this->responseFormat($resultData);
            }else{
                /** 失败 */
                return $this->responseFail('error');
            }
        }
        return $this->responseError('business info not exist');
    }

    /**
     * 重置密码接口
     * @param id 商家Id
     * @param auth_key 认证信息
     * @param password
     */
    public function actionResetpassword()
    {
        /** 校验表单是否为空 */
        if(!$this->postData){
            return $this->responseError("参数信息为空.");
        }
        /** 校验参数信息 */
        if(empty($this->postData['id']) || empty($this->postData['auth_key']) || empty($this->postData['password'])){
            return $this->responseError('id or auth_key or password is null');
        }

        /** 获取商家信息 */
        $business = Business::findIdentity($this->postData['id']);
        if($business){
            if($business->validateAuthKey($this->postData['auth_key'])){

            }
            return $this->responseError('business info not exist');
        }
        return $this->responseError('business info not exist');
    }


}